package com.lzb.compressmaster.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.ViewTreeObserver;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.lzb.compressmaster.BaseAc;
import com.lzb.compressmaster.Content;
import com.lzb.compressmaster.HomeActivity;
import com.lzb.compressmaster.R;
import com.lzb.compressmaster.adapter.ImgListAdapter;
import com.lzb.compressmaster.basic.utils.FileP2pUtil;
import com.lzb.compressmaster.databinding.ActivityImgSpliceBinding;
import com.lzb.compressmaster.dialog.WatermarkDialog;
import com.lzb.compressmaster.utils.ImageVerticalStitcher;
import com.lzb.compressmaster.utils.PhotoPrivacyUtils;
import com.lzb.compressmaster.utils.RxUtil;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.rxjava3.core.ObservableEmitter;

public class ImgSpliceActivity extends BaseAc<ActivityImgSpliceBinding> implements View.OnClickListener, OnItemChildClickListener {

    public static List<String> listPath = new ArrayList<>();
    private ImgListAdapter imgListAdapter;
    private WatermarkDialog watermarkDialog;
    protected boolean isPicTooLarge = false;//判断图片是否过大
    private Bitmap OriBitmap;
    private String text;

    @Override
    protected int onCreate() {
        return R.layout.activity_img_splice;
    }

    @Override
    protected void initView() {
        mDataBinding.ivImgSpliceBack.setOnClickListener(view -> getOnBackPressedDispatcher().onBackPressed());

        mDataBinding.tvImgSort.setOnClickListener(this);
        mDataBinding.tvAdd.setOnClickListener(this);
        mDataBinding.tvWatermark.setOnClickListener(this);
        mDataBinding.tvSave.setOnClickListener(this);

        mDataBinding.rvPictureList.setLayoutManager(new LinearLayoutManager(mContext));
        imgListAdapter = new ImgListAdapter();
        mDataBinding.rvPictureList.setAdapter(imgListAdapter);
        imgListAdapter.addChildClickViewIds(R.id.ivImgListItemDelete);
        imgListAdapter.notifyDataSetChanged();
        imgListAdapter.setOnItemChildClickListener(this);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.tvImgSort) {//图片排序
            ImgSortActivity.type = 1;
            startActivity(ImgSortActivity.class);
        } else if (id == R.id.tvAdd) {//继续添加
            Intent intent = new Intent(this, AddPictureActivity.class);
            intent.putExtra(Content.Again, "Again");
            startActivityForResult(intent, Content.ADD_PICTURE);
        } else if (id == R.id.tvWatermark) {//水印
            showWatermarkDialog();
        } else if (id == R.id.tvSave) {//保存
            save();
        }
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        int id = view.getId();
        if (id == R.id.ivImgListItemDelete) {//删除
            listPath.remove(position);
            imgListAdapter.setList(listPath);
        }
    }

    @Override
    protected void initData() {
        imgListAdapter.setList(listPath);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    //保存
    protected void save() {
        showDialog(getString(R.string.save_ing));
        ImageVerticalStitcher.stitch(mContext, listPath, text, new ImageVerticalStitcher.StitchCallback() {
            @Override
            public void onSuccess(@NonNull String outputPath) {
                FileP2pUtil.copyPrivateImgToPublic(mContext, outputPath);
                dismissDialog();
                ToastUtils.showShort(getString(R.string.save_suc));
                startActivity(HomeActivity.class);
            }

            @Override
            public void onError(@NonNull String err) {

            }
        });
    }


    //设置竖图
    protected void doPinTu() {
        showDialog(getString(R.string.save_ing));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<Bitmap>() {
                    @Override
                    public void doBackground(ObservableEmitter<Bitmap> emitter) {
                        List<Bitmap> listBitmap = imgListAdapter.getListBitmap();
                        isPicTooLarge = false;
                        Bitmap bitmap1 = null;
                        try {
                            bitmap1 = listBitmap.get(0);
                            bitmap1 = ImageUtils.rotate(bitmap1, ImageUtils.getRotateDegree(listPath.get(0)),
                                    bitmap1.getWidth() / 2, bitmap1.getHeight() / 2, true);
                            for (int i = 1; i < listPath.size(); i++) {
                                Bitmap bitmap2 = listBitmap.get(i);
                                bitmap2 = ImageUtils.rotate(bitmap2, ImageUtils.getRotateDegree(listPath.get(i)),
                                        bitmap2.getWidth() / 2, bitmap2.getHeight() / 2, true);
                                bitmap1 = pintu(bitmap1, bitmap2);
                            }
                        } catch (OutOfMemoryError e) {
                            //e.printStackTrace();
                            isPicTooLarge = true;
                        }
                        emitter.onNext(bitmap1);
                    }

                    @Override
                    public void accept(Bitmap bitmap) {
                        dismissDialog();
                        if (isPicTooLarge) {
                            ToastUtils.showShort(R.string.pic_is_too_large);
                            return;
                        }
                        ToastUtils.showShort(getString(R.string.save_suc));
                        //获取要保存的图片bitmap
                        OriBitmap = bitmap;
                        ImageUtils.save2Album(OriBitmap, Bitmap.CompressFormat.PNG);
                        startActivity(HomeActivity.class);
                    }
                });
            }
        }, 1000);
    }

    //竖向
    private Bitmap pintu(Bitmap bitmap1, Bitmap bitmap2) {
        Bitmap ret;
        int width = bitmap1.getWidth();
        if (width > 1024) {
            int h1 = bitmap1.getHeight() * 1024 / bitmap1.getWidth();
            bitmap1 = ImageUtils.scale(bitmap1, 1024, h1, true);
            width = 1024;
        }
        if (bitmap2.getWidth() != width) {
            int h2 = bitmap2.getHeight() * width / bitmap2.getWidth();
            ret = Bitmap.createBitmap(width, bitmap1.getHeight() + h2, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(ret);
            Bitmap newSizeBitmap2 = ImageUtils.scale(bitmap2, width, h2, true);
            canvas.drawBitmap(bitmap1, 0, 0, null);
            canvas.drawBitmap(newSizeBitmap2, 0, bitmap1.getHeight(), null);
        } else {
            ret = Bitmap.createBitmap(width, bitmap1.getHeight() + bitmap2.getHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(ret);
            canvas.drawBitmap(bitmap1, 0, 0, null);
            canvas.drawBitmap(bitmap2, 0, bitmap1.getHeight(), null);
        }
        return ret;
    }

    private void showWatermarkDialog() {
        if (watermarkDialog == null) watermarkDialog = new WatermarkDialog(mContext);
        watermarkDialog.setListener(new WatermarkDialog.Ilistener() {
            @Override
            public void clickConfirm(String name) {
                text = name;
            }
        });
        watermarkDialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            List<String> list = data.getStringArrayListExtra(Content.path);
            if (requestCode == Content.ADD_PICTURE) {
                listPath.addAll(list);
            }
            imgListAdapter.setList(listPath);
        }
    }

}